package server

import (
	"github.com/cz-it/gonnectd/utils/log"

	"net"
)

const (
	BUFSIZE = 7 * 1024
)

type Line struct {
	Buffer []byte
	Conn   net.Conn
	Svr    *Server
/*
	Req    *Request
	Rep    *Response
*/
}

func NewConn(conn net.Conn, svr *Server) *Line {
	l := new(Line)
	l.Conn = conn
	l.Svr = svr
/*
	l.Req = new(Request)
	l.Req.r = conn

	l.Rep = new(Response)
	l.Rep.w = conn
*/
//	l.Buffer = make([]byte, proto.MAX_PKG_LEN)
	return l
}

func (l *Line) Serve() {
	for {
		l.readRequest()
		l.procpkg()
		cmd := uint8( 127)
		buf := make([]byte,127)
		l.writeResponse(cmd, buf)
		break
	}
}

func (l *Line) Close() {
	log.Info("Close one connect:fd %d client ip:%s",1,"127.0.0.1:8008")
	l.Conn.Close()
}

func (l *Line) readRequest()/* *proto.Package*/ {
//	pkg := l.Req.Read(l.Buffer)
//	log.Debug("Read package is :", pkg)
//	return pkg
	return 
}

func (l *Line) procpkg(/*pkg *proto.Package*/) (cmd uint8, buf []byte) {
	// check magic first
/*
	if proto.MAGIC != pkg.Head.Magic {
		log.Error("Not valied magic")
		cmd = proto.CMD_REP_FIN
		l.Close()
	}
	// look up for version
	if proto.VERSION != pkg.Head.Version {
		log.Error("Not valied version")
		cmd = proto.CMD_REP_FIN
		l.Close()
	}


	var hdl handler.Handler

	switch pkg.Head.Cmd {
	case proto.CMD_REQ_SYN:
		cmd = proto.CMD_REP_SYN
		hdl = handler.NewSyn()

	case proto.CMD_REQ_FIN:
		cmd = proto.CMD_REP_FIN
		l.Close()
		return
	}
	if hdl != nil {
		buf = hdl.Proc(pkg.Body)
	} else {
		// invalied request ,close directly
		cmd = proto.CMD_REP_FIN
		l.Close()
	}
*/
	return 0,nil
}

func (l *Line) writeResponse(cmd uint8, buf []byte) {
	//Logger.Debug("write buf is :",buf)
	//l.Rep.Write(cmd, buf)
	return
}
